﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Data;


namespace guosange.Common
{
    public class CXMLAccess
    {
        protected string strXMLFile;

        public XmlDocument objXMLDoc = new XmlDocument();


        public CXMLAccess(string XMLFile)
        {
            // 
            // TODO: 在這裡加入建構函式的程式碼 
            // 
            try
            {
                //if (!File.Exists(XMLFile))
                //{
                //    XmlDeclaration dec = objXMLDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                //    objXMLDoc.AppendChild(dec);
                //    XmlElement root = objXMLDoc.CreateElement("QUnitTest");
                //    objXMLDoc.AppendChild(root);
                //    objXMLDoc.Save(XMLFile);
                //}
                objXMLDoc.Load(XMLFile);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            strXMLFile = XMLFile;
        }

        /// <summary>
        /// Write Data to the XML File
        /// </summary>
        /// <PARAM name="Section"></PARAM>
        /// Section name
        /// <PARAM name="Key"></PARAM>
        /// Key Name
        /// <PARAM name="Value"></PARAM>
        /// Value Name
        //
        public void WirteXMLValue(string KeySection, string Key, string Value)
        {
            string path = KeySection + @"/" + Key;
            XmlNode ste = this.GetNode(path);
            if (ste == null)
            {
                this.InsertElement(KeySection, Key, "value", Value);
            }
            else
            {
                ste.Attributes[0].Value = Value;
            }
            //this.Save();
        }

        public void WirteXMLValue(string KeySection, string Key, string attributeName, string Value)
        {
            string path = KeySection + @"/" + Key;
            XmlNode ste = this.GetNode(path);
            if (ste == null)
            {
                this.InsertElement(KeySection, Key, "value", Value);
            }
            else
            {
                ste.Attributes[attributeName].Value = Value;
            }
            //this.Save();
        }

        /// <summary>
        /// Read Data Value From the XML File,power by TonySu,adapt by LinDu
        /// </summary>
        /// <PARAM name="Section"></PARAM>
        /// <PARAM name="Key"></PARAM>
        /// <PARAM name="Path"></PARAM>
        /// <returns></returns>

        public string ReadXMLValue(string KeySection, string Key, string DefaultValue)
        {
            string path = KeySection + @"/" + Key;
            XmlNode ste = this.GetNode(path);

            if (ste == null)
            {
                return DefaultValue;
            }
            else
                return ste.InnerText.Trim();
        }

        public DataSet GetData(string XMLPathNode)
        {
            try
            {
                DataSet ds = new DataSet();
                DataTable table = new DataTable("temptable");
                DataColumn column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = "temp";
                // Add the Column to the DataColumnCollection.
                table.Columns.Add(column);
                for (int i = 0; i < objXMLDoc.SelectNodes(XMLPathNode).Count; i++)
                {
                    DataRow row = table.NewRow();
                    row["temp"] = objXMLDoc.SelectNodes(XMLPathNode)[i].InnerText;
                    table.Rows.Add(row);
                }
                ds.Tables.Add(table);
            
                return ds;
            }
            catch (Exception ee)
            {
                throw ee;
            }
        }

        public void Replace(string XMLPathNode, string Content)
        {
            try
            {
                //更新節點內容。 
                if (Content != "")
                {
                    objXMLDoc.SelectSingleNode(XMLPathNode).InnerText = Content;
                }
                else
                {
                    try
                    {
                        objXMLDoc.SelectSingleNode(XMLPathNode).InnerText = null;
                    }
                    catch (Exception ee)
                    {
                        throw ee;
                    }
                }
            }
            catch (Exception ee)
            {
                throw ee;
            }
        }

        public void Delete(string Node)
        {
            //刪除1/X個節點。 
            string mainNode = Node.Substring(0, Node.LastIndexOf("/"));
            try
            {
                XmlNodeList nodelist = objXMLDoc.SelectNodes(Node);
                for (int i = 0; i < nodelist.Count; i++)
                {
                    objXMLDoc.SelectSingleNode(mainNode).RemoveChild(objXMLDoc.SelectSingleNode(Node));
                }
            }
            catch (System.Exception ee)
            {
                throw ee;
            }
        }

        public void InsertNode(string MainNode, string ChildNode, string Element, string Content)
        {
            //插入一節點和此節點的一子節點。 

            try
            {
                XmlNode objRootNode = objXMLDoc.SelectSingleNode(MainNode);
                XmlElement objChildNode = objXMLDoc.CreateElement(ChildNode);
                objRootNode.AppendChild(objChildNode);
                XmlElement objElement = objXMLDoc.CreateElement(Element);
                objElement.InnerText = Content;
                objChildNode.AppendChild(objElement);
            }
            catch (System.Exception ee)
            {
                throw ee;
            }
        }


        public void InsertElement(string MainNode, string Element, string Attrib, string AttribContent, string Content)
        {
            //插入一個節點，帶一屬性。 
            try
            {
                XmlNode objNode = objXMLDoc.SelectSingleNode(MainNode);
                XmlElement objElement = objXMLDoc.CreateElement(Element);
                objElement.SetAttribute(Attrib, AttribContent);
                objElement.InnerText = Content;
                objNode.PrependChild(objElement);
            }
            catch (System.Exception ee)
            {
                throw ee;
            }
        }

        //
        public void InsertElement(string MainNode, string Element, string Attrib, string AttribContent)
        {
            //插入一個節點，帶一屬性。 
            try
            {
                XmlNode objNode = objXMLDoc.SelectSingleNode(MainNode);
                XmlElement objElement = objXMLDoc.CreateElement(Element);
                objElement.SetAttribute(Attrib, AttribContent);
                
                objNode.PrependChild(objElement);
            }
            catch (System.Exception ee)
            {
                throw ee;
            }
        }


        public void InsertElement2(string MainNode, string Element, string Attrib, string AttribContent, string Attrib1, string AttribContent1, string Content)
        {
            //插入一個節點，帶二个屬性。 
            try
            {
                XmlNode objNode = objXMLDoc.SelectSingleNode(MainNode);
                XmlElement objElement = objXMLDoc.CreateElement(Element);
                objElement.SetAttribute(Attrib, AttribContent);
                objElement.SetAttribute(Attrib1, AttribContent1);
                objElement.InnerText = Content;
                objNode.PrependChild(objElement);
            }
            catch (System.Exception ee)
            {
                throw ee;
            }
        }

        public void InsertElementfirst(string MainNode, string Element, string Content)
        {
            //插入一個節點，不帶屬性。 
            try
            {
                XmlNode objNode = objXMLDoc.SelectSingleNode(MainNode);
                XmlElement objElement = objXMLDoc.CreateElement(Element);
                objElement.InnerText = Content;
                objNode.PrependChild(objElement);//加到子节点的开头
            }
            catch (System.Exception ee)
            {
                throw ee;
            }
        }

        public void InsertElementlast(string MainNode, string Element, string Content)
        {
            //插入一個節點，不帶屬性。
            try
            {
                XmlNode objNode = objXMLDoc.SelectSingleNode(MainNode);
                XmlElement objElement = objXMLDoc.CreateElement(Element);
                objElement.InnerText = Content;
                objNode.AppendChild(objElement);
            }
            catch (System.Exception ee)
            {
                throw ee;
            }
        }

        //得到最大的节点的ID，第一条记录
        public int GetMaxID(string XMLPathNode)
        {
            int id=Int32.Parse((objXMLDoc.SelectSingleNode(XMLPathNode).Attributes["leavewordid"].Value));
            return id;
        }

        
        public string Get(string XMLPathNode)
        {
            try
            {
                XmlNodeList nodelist = objXMLDoc.SelectNodes(XMLPathNode);
                string content="";

                if (nodelist.Count > 0)
                {
                    content = nodelist[0].InnerText;
                    return content;
                }
               
            }
            catch (System.Exception ee)
            {
                throw ee;
            }
            return "";
        }

        #region 获取指定XPath表达式的节点对象
        /// <summary>
        /// 获取指定XPath表达式的节点对象
        /// </summary>        
        /// <param name="xPath">XPath表达式,
        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
        /// </param>
        public XmlNode GetNode(string xPath)
        {
            //返回XPath节点
            return objXMLDoc.SelectSingleNode(xPath);
        }

        private XmlNodeList GetNodes(string xPath)
        {
            return objXMLDoc.SelectNodes(xPath);
        }
        #endregion

        public List<string> GetNodesAttributeValue(string xPath, params string[] attributeName)
        {
            List<string> listStr = new List<string>();
            if (attributeName == null)
                return listStr;
            XmlNodeList xmlList = GetNodes(xPath);

            foreach (XmlNode node in xmlList)
            {
                foreach (string str in attributeName)
                {
                    listStr.Add(node.Attributes[str].InnerText.NotNullString());
                }
            }

            return listStr;
        }

        #region 获取指定XPath表达式节点的属性值
        /// <summary>
        /// 获取指定XPath表达式节点的属性值
        /// </summary>
        /// <param name="xPath">XPath表达式,
        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
        /// </param>
        /// <param name="attributeName">属性名</param>
        public string GetAttributeValue(string xPath, string attributeName)
        {
            //返回XPath节点的属性值
            return objXMLDoc.SelectSingleNode(xPath).Attributes[attributeName].Value.NotNullString();
        }

        public string GetAttributeValue(string xPath, string attributeName, string defaulteValue)
        {
            string str = objXMLDoc.SelectSingleNode(xPath).Attributes[attributeName].Value.NotNullString();
            if (string.IsNullOrEmpty(str))
            {
                return defaulteValue;
            }
            //返回XPath节点的属性值
            return str;
        }
        #endregion

        public void Save()
        {
            //保存文檔。
            try
            {
                objXMLDoc.Save(strXMLFile);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            //objXMLDoc = null;
        }
    } 

}